package club.xyes.zkh.ecommerce.service.impl;

import club.xyes.zkh.ecommerce.commons.entity.WxFormId;
import club.xyes.zkh.ecommerce.commons.exception.InternalServerErrorException;
import club.xyes.zkh.ecommerce.dao.mapper.WxFormIdMapper;
import club.xyes.zkh.ecommerce.service.WxFormIdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Create by 郭文梁 2019/5/6 0006 13:15
 * WxFormIdServiceImpl
 * 微信FormId业务行为实现
 *
 * @author 郭文梁
 * @data 2019/5/6 0006
 */
@Service
public class WxFormIdServiceImpl extends BaseServiceImpl<WxFormId> implements WxFormIdService {
    private final WxFormIdMapper mapper;

    @Autowired
    public WxFormIdServiceImpl(WxFormIdMapper mapper) {
        super(mapper);
        this.mapper = mapper;
    }

    @Override
    public WxFormId collect(String appId, String openId, String formId) {
        WxFormId target = new WxFormId();
        target.setAppId(appId);
        target.setOpenId(openId);
        target.setFormId(formId);
        return save(target);
    }

    @Override
    public List<WxFormId> collect(String appId, String openId, List<String> formIds) {
        List<WxFormId> ids = formIds.stream()
                //去重
                .distinct()
                .map(formId -> {
                    WxFormId target = new WxFormId();
                    target.setAppId(appId);
                    target.setOpenId(openId);
                    target.setFormId(formId);
                    return target;
                }).collect(Collectors.toList());
        return save(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxFormId popOne(String appId, String openId) {
        WxFormId formId = mapper.selectOneByAppIdAndOpenId(appId, openId);
        if (formId == null) {
            return null;
        }
        boolean deleteResult = deleteById(formId.getId());
        if (!deleteResult) {
            throw new InternalServerErrorException("Unable to delete formId for id " + formId.getId());
        }
        return formId;
    }

    @Override
    public int cleanExpired() {
        return mapper.deleteExpired();
    }
}
